<!-- 附件信息 -->
<template>
  <div ref="attachmentListRef" class="attachmentList">
    <SearchList title="工程资料全览">
      <template #body>
        <MyTable
          id="fileId"
          ref="myTableRef"
          :is-mar-class="true"
          :table-data="tableData"
          :columns="colOptionC"
          :table-operation="btnOptionB"
          :col-option-enum="dicLists"
          @propClick="btnClick"
        >
          <template #fileName="{ scope }">
            <el-button type="text" @click="preview(scope)">{{ scope.fileName }}</el-button>
          </template>
        </MyTable>
      </template>
    </SearchList>
    <!-- 文件预览 -->
    <el-dialog
      v-if="dialogFileView"
      ref="dialogViewRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      :lock-scroll="true"
      title="预览"
      height="60%"
      width="60%"
      class="pms-zr-dialog"
      :visible.sync="dialogFileView"
      @close="dialogClosed"
    >
      <div class="signatoryPre">
        <FilePreview ref="filePreviewRef" class="filePreviewClass" :file-obj="fileObj" />
      </div>
      <div slot="footer" class="pms-zr-dialog-footer">
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="() => { dialogFileView = false; dialogClosed() }"
        >
          取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import MyTable from '@/components/basic/myTable'
import FilePreview from '@/components/business/filePreview.vue'
import { colOptionC, btnOptionB } from './index'
import { getDropdownData } from '@/api/common' // 字典接口
import { getQueryObject, disableScroll, enableScroll, msgInfoEl, downloadFileFun } from '@/utils' // singleDownload, mulDownload,
import { getSignFlowDocUrlsApi } from '@/api/attachManagement/electronicSign/electronicSignature'
import {
    queryAttachmentOverview,
    getPrjStageApi,
    batchDownloadApi, // 批量下载
    downloadApi, getPreviewFile, getWPSToken, querySuffix // 单个文件下载
} from '@/api/attachmentInfo'
import SearchList from '@/components/basic/SearchList.vue'
import $ from 'jquery'
const Base64 = require('js-base64').Base64

export default {
    name: 'AttachmentFullView',
    components: {
        SearchList,
        MyTable,
        FilePreview
    },
    filters: {
        prjFileType(data) {
            if (!data.length) {
                return ''
            } else {
                const list = data.filter((item) => item.isMust === '1')
                const filterList = list.map(item => item.typeName)
                const customCheck = filterList.join().replaceAll(',', '、')
                return customCheck
            }
        }
    },
    data() {
        return {
            tableData: [], // 附件列表数据
            wpsToken: '',
            colOptionC, // 附件表头
            prjParams: {}, // 页面路由参数集
            dicLists: {}, // 字典数据集合
            fileObj: {}, // 预览文件地址
            previewObj:{},
            dialogFileView: false, // 预览弹框
            btnOptionB
        }
    },
    created() {
        this.getDictData()
        this.getPrjStage()
        const {
            prjId,
            prjStage
        } = getQueryObject()
        this.prjParams = {
            prjId, // 项目id
            prjStage
        }
        this.doSearch()
        this.getToken()
        this.querySuffix()
    },
    methods: {
        querySuffix() {
            querySuffix().then((res) => {
                if (+res.code === 200) {
                    this.previewObj = res.data
                }
            })
        },
        getToken() {
            getWPSToken().then((res) => {
                if (+res.code === 200) {
                    this.wpsToken = res.data
                }
            })
        },
        // 查看数据
        doSearch() {
            const params = {
                prjId: this.prjParams.prjId,
                prjStage: this.prjParams.prjStage
            }
            queryAttachmentOverview(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                } else {
                    this.tableData = res.data
                }
            })
        },
        // 当父组件接收到了子组件this.$emit的通知后就会执行这个方法来接收子组件点击传递过来的数据
        btnClick(fun, row) {
            this[fun](row)
        },
        // 下载
        download(row) {
            console.log(row, '下载--row')
            const fileDownloadNo = row.find(item => item.fileId === '' || item.fileId === null || item.fileId === undefined) || {}
            if (JSON.stringify(fileDownloadNo) !== '{}') {
                return msgInfoEl({
                    type: 'info',
                    message: `当前选择范围中存在未上传文件，请上传或取消勾选该文件再进行下载`
                })
            }
            const fileName = row.length > 1 ? '附件信息.zip' : row[0].fileName
            // 单个文件下载时的参数
            const params = {
                fileId: row[0].fileId,
                fileName: row[0].fileName
            }
            // 多个文件下载时的参数
            const batchParams = row.map(item => ({
                fileId: item.fileId,
                fileName: item.fileName
            }))
            if (row.length > 1) {
                // mulDownload(row, fileName)
                // 批量下载
                batchDownloadApi({ fileMap: batchParams }).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            } else {
                // singleDownload(row, fileName)
                // 单个文件下载
                downloadApi(params).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            }
        },
        getUserId(){
            let str='';
            if(sessionStorage.getItem('SET_LOGINDATA')){
              str = JSON.parse(sessionStorage.getItem('SET_LOGINDATA')).staffId
            }else if(sessionStorage.getItem('userInfo')){
              str = JSON.parse(sessionStorage.getItem('userInfo')).staffId
            }else{
              console.log('')
            }
            console.log('str',str)
            return str;
        },
        // 点击文件名称-预览
        async preview(row) {
            if (row.isSignature === '1') {
                this.getSignFlowDocUrls(row.fileViewId)
                return
            } else {
                const types = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
                const previewArray = Object.keys(this.previewObj);
                if (previewArray.includes(types)) {
                    const params = {
                        fileId: row.fileId,
                        type: this.previewObj[types],
                        userId: this.getUserId(),
                        token: this.wpsToken
                    }
                    getPreviewFile(params).then((res) => {
                        // if(+res.code===200){
                        //     const newWin = window.open()
                        //     const form = $("<form method='post'></form>")
                        //     form.attr({ action: res.data })
                        //     form.appendTo(newWin.document.body)
                        //     form.submit()
                        // }
                        if (+res.code === 200 && res.data) {
                            window.open(res.data, '_blank')
                        }
                    })
                } else {
                    return msgInfoEl({
                        type: 'info',
                        message: `所选文件不支持预览`
                    })
                }
            }
            // let res = {}
            // const params = {
            //     fileId: row.fileId,
            //     fileName: row.fileName
            // }
            // await downloadApi(params).then(r => {
            //     res = r
            // })
            // const blob = new Blob([res.data], { type: 'application/pdf;charset-UTF-8' })
            // const url = window.URL.createObjectURL(blob)
            // row.filePath = url
            // this.fileObj = {}
            // if (!row.filePath) {
            //     return msgInfoEl({
            //         type: 'info',
            //         message: `所选${row.fileName}文件不支持预览`
            //     })
            // }
            // const types = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
            // if (['word', 'docx', 'excel', 'xlsx'].includes(types)) {
            //     console.log(types, '12')
            //     window.open(this.$router.resolve({
            //         name: 'FilePreview',
            //         query: {
            //             type: types,
            //             fileSrc: row.filePath
            //         }
            //     }).href, '_blank')
            //     return
            // }
            // if (['pdf'].includes(types)) {
            //     window.open(row.filePath, '_blank')
            //     return
            // }
            // if (['pptx', 'ppt', 'xls', 'doc'].includes(types)) {
            //     // window.open(`${process.env.VUE_APP_BASE_API}preview/onlinePreview?url=${encodeURIComponent(Base64.encode(row.filePath))}`, '_blank')
            //     return msgInfoEl({
            //         type: 'info',
            //         message: `所选文件不支持预览`
            //     })
            // }
            // if (['jpg', 'png', 'jpeg', 'bmp', 'mp3', 'mp4', 'webm', 'ogg', 'aac', 'wav'].includes(types)) {
            //     this.fileObj = {
            //         type: types,
            //         fileSrc: row.filePath
            //     }
            //     this.dialogFileView = true
            //     this.dialogEl('dialogViewRef')
            // } else if (['txt'].includes(types)) {
            //     axios.get(row.filePath, {
            //         responseType: 'blob',
            //         transformResponse: [
            //             async function(data) {
            //                 // txt转码
            //                 return await new Promise((resolve) => {
            //                     const reader = new FileReader()
            //                     reader.readAsText(data, 'UTF-8') // GBK UTF-8
            //                     reader.onload = () => {
            //                         resolve(reader.result)
            //                     }
            //                 })
            //             }
            //         ]
            //     }).then(res => {
            //         res.data.then((data) => {
            //             this.fileObj = {
            //                 type: types,
            //                 fileSrc: data
            //             }
            //         })
            //     })
            //     this.dialogFileView = true
            //     this.dialogEl('dialogViewRef')
            // } else {
            //     msgInfoEl({
            //         type: 'info',
            //         message: '不支持预览此文件'
            //     })
            // }
            // console.log(row, types, '预览')
        },
        // 电子签章预览
        getSignFlowDocUrls(id) {
            getSignFlowDocUrlsApi({ id }).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                if (res.data) {
                    // window.open(res.data, '_blank')
                    axios.get(res.data, {
                        responseType: 'blob',
                        cache: true,
                        headers: {
                            'Content-Disposition': 'inline'
                        }
                    }).then(r => {
                        const blob = new Blob([r.data], { type: 'application/pdf;charset-UTF-8' })
                        // const blob = new Blob([r.data], { type: r.headers['content-type'] })
                        const url = window.URL.createObjectURL(blob)
                        window.open(url, '_blank')
                        URL.revokeObjectURL(url) // 释放内存
                    })
                }
            })
        },
        // 获取下拉框字典数据
        async getDictData() {
            const arr = ['SIGN_STATE2']
            const promises = arr.map(item => getDropdownData(item))
            const results = await Promise.all(promises)
            arr.forEach((item, i) => {
                this.$set(this.dicLists, item, results[i].data ?? [])
            })
        },
        // 获取项目阶段字典
        async getPrjStage() {
            const res = await getPrjStageApi()
            const stageData = res.data.map(item => ({
                dictId: item.key,
                dictName: item.value
            }))
            this.$set(this.dicLists, 'PRO_STAGE', stageData)
        },
        // 将弹框挂载在最外层
        dialogEl(refName) {
            // 将弹框挂载在最外层
            const contentBody = window.top.document.body
            this.$nextTick(() => {
                const dialogModal = document.querySelector('.v-modal')
                contentBody.appendChild(this.$refs[refName].$el)
                contentBody.appendChild(dialogModal)
                disableScroll(contentBody)
            })
        },
        // 关闭弹框
        dialogClosed() {
            const contentBody = window.top.document.body
            enableScroll(contentBody)
        }
    }
}
</script>

<style lang="scss" scoped>
.attachmentList {
    height: auto;
}

.el-button--text {
    color: #02A7F0;
}

.el-button--primary {
    color: #fff;
}

.el-button--mini {
    color: #fff;
}

.signatoryBody {
    min-height: 170px;
    max-height: 420px;
    overflow-y: auto;
    overflow-x: hidden;
}

.signatoryPre {
    max-height: 420px;
    overflow-y: auto;
    overflow-x: hidden;
}

.el-collapse {
    margin-bottom: 20px;
}

.el-collapse-item {
    box-shadow: 0px 0px 6px 0px rgba(191, 192, 192, 0.52);
    /* 调整各个item之间的距离为20px */
    /* border: 1px; */
}

.el-collapse-item__wrap {
    padding: 0 20px;
    /* 为el-collapse-item的内容添加20像素的padding */
}

.el-collapse-item__header {
    padding-left: 20px;
    font-size: 14px;
    color: #333333;
    letter-spacing: 0;
    font-weight: 600;
}

.item_icon {
    width: 6px;
    background: rgb(235, 75, 75);
    height: 15px;
    margin-right: 10px;
    border-radius: 10px;
}

.content-box {
    width: 100%;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 400;
    line-height: 25px;
}

.headerLeft {
    font-size: 14px;

    .headerLeftTitle {
        color: #D9001B;
    }
}
</style>
